import asyncio
import datetime
import json
import time
from fastapi import APIRouter, HTTPException
from typing import Optional, Any
from pydantic import BaseModel

from settings.settings import settings

from sockets.agvsocket import AgvSocket

from timers.scheduler import MyScheduler

from events.status import init_status_event

agv_so_manage = AgvSocket()

# 创建audio_router路由
base_router = APIRouter()

scheduler = MyScheduler().scheduler


class StatusParams(BaseModel):
    play: int

    class Config:
        schema_extra = {
            "example": {
                "flag": 1,
            }
        }


@base_router.get("/")
async def base_control(flag: int):
    if flag == 1:
        scheduler.add_job(tick2, 'interval', seconds=5, id='audio')
        return 'add job success'
    elif flag == 2:
        scheduler.remove_job('audio')
        return 'delete job success'
    # 连接agv
    elif flag == 3:
        # 初始化 agv socket
        flag2 = AgvSocket().init_socket_pool()
        if flag2:
            print('server-->agv,success!!!')
            # 先清除定时器里面所有的任务,然后重建添加任务,要不然会抛出重复任务的异常
            scheduler.remove_all_jobs()
            await init_status_event()
            return 'agv 连接成功'
        else:
            print('server-->agv,fail!!!')
            return 'agv 连接失败'
    # 断开agv
    elif flag == 4:
        # 清除定时器里面的所有任务,然后主动断开与agv的连接
        scheduler.remove_all_jobs()
        AgvSocket().close_socket_pool()
        return '断开agv连接'

    # so = agv_so_manage.get(19210)
    # if so is not None:
    #     agv_so_manage.send(so, 1, 6000)
    #     print(agv_so_manage.receive(so))
    #     return 'fa song'
    # else:
    #     print('agv没有开启连接')
    #     return 'disconnect'


async def tick2():
    print('audio Tick! The time is: %s' % datetime.datetime.now())
    await asyncio.sleep(1)
